package com.caltco.cargo.ops.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;


import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @program: agilefast-framework
 * @description: JSON相关工具类
 * @author: yehao
 * @create: 2022-07-28 17:06
 **/

public class JSONUtils  {

    public static <T> void JSON2Bean(JSONObject jsonObject, T t) {
        Field[] declaredFields = t.getClass().getDeclaredFields();
        // 获取实体属性，过滤掉json对象中不属于此对象的key
        Set<String> collect = Arrays.asList(declaredFields).stream().map(it -> it.getName()).collect(Collectors.toSet());
        jsonObject.entrySet().stream()
                .filter(item -> collect.contains(StrUtil.toCamelCase(item.getKey())))
                .forEach(item -> BeanUtil.setProperty(t, StrUtil.toCamelCase(item.getKey()), item.getValue()));
    }
}
